#!/usr/bin/env python3
"""
Final fix script to clean up remaining LaTeX issues
"""

import os
import re
from pathlib import Path

def final_fix_file(filepath):
    """Apply final fixes to a LaTeX file"""
    print(f"Final fixing {filepath}")
    
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            content = f.read()
        
        original_content = content
        
        # Fix duplicate placement specifiers
        content = re.sub(r'\[H\]\[H\]', r'[H]', content)
        content = re.sub(r'\[H\]\[htbp\]', r'[H]', content)
        content = re.sub(r'\[htbp\]\[H\]', r'[H]', content)
        
        # Fix any remaining broken hyperref settings
        content = re.sub(r'colorlinks=true,\n    linkcolor=blue,\n    filecolor=magenta,\n    urlcolor=cyan,\n    citecolor=green,', 
                        'colorlinks=true,\n    linkcolor=blue,\n    filecolor=magenta,\n    urlcolor=cyan,\n    citecolor=green,', content)
        
        # Write the fixed content if changed
        if content != original_content:
            with open(filepath, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"  Final fixed {filepath}")
            return True
        else:
            print(f"  No final fixes needed for {filepath}")
            return False
            
    except Exception as e:
        print(f"  Error final fixing {filepath}: {e}")
        return False

def main():
    """Main final fix function"""
    print("LaTeX Final Fix Script")
    print("=" * 25)
    
    # Get current directory
    base_dir = Path('.')
    
    # Find all .tex files
    tex_files = []
    
    # Main document
    main_doc = base_dir / 'cpp-function-call-tree-report.tex'
    if main_doc.exists():
        tex_files.append(main_doc)
    
    # Chapter files
    chapters_dir = base_dir / 'chapters'
    if chapters_dir.exists():
        tex_files.extend(chapters_dir.glob('*.tex'))
    
    if not tex_files:
        print("No .tex files found!")
        return
    
    processed_count = 0
    fixed_count = 0
    
    for tex_file in tex_files:
        processed_count += 1
        if final_fix_file(tex_file):
            fixed_count += 1
    
    print("-" * 20)
    print(f"Final fixes complete!")
    print(f"Files processed: {processed_count}")
    print(f"Files fixed: {fixed_count}")
    
    # Try final compilation
    print("\nTrying final compilation...")
    import subprocess
    try:
        result = subprocess.run(
            ['xelatex', '-interaction=nonstopmode', 'cpp-function-call-tree-report.tex'],
            capture_output=True,
            text=True,
            timeout=60
        )
        
        if result.returncode == 0:
            print("✅ Final compilation successful!")
        else:
            print("⚠️  Final compilation completed with some warnings")
            
    except Exception as e:
        print(f"❌ Final compilation error: {e}")

if __name__ == '__main__':
    main()